package com.mihuo.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

@Service
public class AsyncServiceDemo {

    // 无返回值任务
    @Async("customTaskExecutor")
    public void processTask(String data) {
        // 模拟耗时操作，如发送邮件、处理文件
        System.out.println("处理任务: " + data + ", 线程: " + Thread.currentThread().getName());
    }

    // 有返回值任务 - 使用 CompletableFuture (推荐)
    @Async("customTaskExecutor")
    public CompletableFuture<String> processTaskWithResult(int taskId) {
        try {
            Thread.sleep(1000); // 模拟处理
            return CompletableFuture.completedFuture("任务" + taskId + "完成");
        } catch (InterruptedException e) {
            return CompletableFuture.completedFuture(null);
        }
    }

    // 有返回值任务 - 使用 Future (传统方式)
    @Async("customTaskExecutor")
    public Future<String> processTaskWithOldFuture(int taskId) {
        try {
            Thread.sleep(1000);
            return new AsyncResult<>("结果:" + taskId);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return new AsyncResult<>("错误");
        }
    }
}